<template>
  <div class="exercises-box inner-content">
    <div class="inner inner-content-box">
      <el-form class="search-form" :inline="true" :model="searchForm" @keyup.enter.native="getDataList(1)">
        <el-form-item>
          <el-input v-model="searchForm.examName" placeholder="题目名称" clearable style="width: 160px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.examTypeName" placeholder="科室名称" clearable style="width: 160px"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="flex-start" style="align-items: flex-start">
            <el-button type="primary" @click="getDataList(1)" icon="el-icon-search">查询</el-button>
            <el-button @click="clearHandle()" icon="el-icon-delete-solid">清空</el-button>
          </div>
        </el-form-item>
        <br />
        <el-form-item>
          <div class="flex-start" style="align-items: flex-start">
            <el-button type="primary" icon="el-icon-edit">自定义试题</el-button>
            <el-button type="warning" icon="el-icon-plus" @click="showExercises">创建习题</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="table-box" ref="tableBox">
        <el-table :data="dataList" :height="tableHeight" border size="small" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="序号" type="index" fixed="left" header-align="center" align="center" width="70">
          </el-table-column>
          <el-table-column minWidth="130" prop="examName" header-align="center" align="center" label="项目名称">
          </el-table-column>
          <el-table-column minWidth="230" prop="examText" header-align="center" align="center" label="习题题干"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column width="90" prop="examTypeName" header-align="center" align="center" label="科室名称">
          </el-table-column>

          <el-table-column width="80" prop="createOperator" header-align="center" align="center" label="管理员">
          </el-table-column>
          <el-table-column width="160" prop="createTime" header-align="center" align="center" label="创建时间">
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button title="删除" icon="el-icon-delete" type="danger" circle size="small"
                @click='delItem(scope.row)'></el-button>
              <el-button title="详情" icon="el-icon-view" type="primary" circle size="small"
                @click="edit(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex-end">
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="习题" :lock-scroll="false" :close-on-click-modal="false" :fullscreen="true"
      :visible.sync="exercisesDialog" width="800px">
      <div class="top-box">
        <div class="title">
          基本信息
          <div>
            <el-button type="primary" @click="exercisesFormSubmit('exercisesForm')" size="small"
              :loading="saveLoading">保存</el-button>
          </div>
        </div>
        <el-form :model="exercisesForm" :rules="exercisesFormRules" ref="exercisesForm" label-width="160px"
          style="padding-right: 30px;"
          label-position="right">
          <el-row>
            <el-col :sm="24" :md="12">
              <el-form-item label="科室名称：" prop="dept">
                <el-select style="width: 300px" v-model="exercisesForm.dept" placeholder="请选择科室"
                  :remote-method="getDept" @change="deptChange" :loading="deptLoading" filterable clearable remote
                  reserve-keyword>
                  <el-option v-for="item in deptOptions" :key="item.id" :label="item.dept" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12">
              <el-form-item label="项目名称：" prop="examNameCode">
                <el-select style="width: 300px" v-model="exercisesForm.examNameCode" placeholder="请选择项目名称" filterable
                  clearable>
                  <el-option v-for="item in examOptions" :key="item.id" :label="item.examName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12">
              <el-form-item label="习题题干：" prop="examText">
                <el-input style="min-width: 340px" v-model="exercisesForm.examText" placeholder="请填写习题题干" size="small"
                  type="textarea" rows="8">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12">
              <el-form-item label="注意事项及说明：" prop="examPoints">
                <el-input style="min-width: 340px" v-model="exercisesForm.examPoints" placeholder="请填写注意事项及说明"
                  size="small" type="textarea" rows="8">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="操作视频：" prop="examVideoUrl">
                <div class="flex" style="justify-content: flex-start;align-items: center;margin-bottom: 4px">
                  <!-- <input type="file"  @change="videoChange" accept="video/*"> -->
                  <el-upload
                    :action="url"
                    :headers="headerToken"
                    :on-success="successHandle"
                    :before-upload="beforeUploadHandle"
                    :on-progress="handleProgress"
                    :show-file-list="false"
                    accept="video/*"
                  >
                  <el-button>上传视频</el-button>
                  </el-upload>
                  <div v-if="uploadProgress !==0 && uploadProgress !==100">
                    <progress :value="uploadProgress" max="100" style="width: 60px;margin: 0 4px;">{{ uploadProgress }}%</progress>
                    上传进度 {{ uploadProgress }}%
                  </div>
                </div>
                <video style="width: 300px; height: 240px; background: #f7f7f7;" ref="video" :src="exercisesForm.examVideoUrlBak" autoplay></video>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="视图预览图：" prop="examVideoUrl">
                <img :src="exercisesForm.examImageUrl" alt="" ref="image" style="max-height: 240px;max-width: 200px;margin-top: 30px;">
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="时长：" prop="examVideoUrl">
                {{ exercisesForm.examVideoTime }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="top-box bottom-box">
        <p class="title">上传信息</p>
        <div class="tab-inner">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="添加评分卡" name="scoreCard">
              <scoreCard :examinationId="exercisesForm.id" ref="childScoreCard"></scoreCard>
            </el-tab-pane>
            <el-tab-pane label="添加自检卡及装箱单" name="selfinspectionCard">
              <selfinspectionCard :examinationId="exercisesForm.id" ref="childSelfinspectionCard"></selfinspectionCard>
            </el-tab-pane>
            <el-tab-pane label="添加提示卡" name="cueCard">
              <cueCard :examinationId="exercisesForm.id" ref="childCueCard"></cueCard>
            </el-tab-pane>
            <el-tab-pane label="添加重要知识点" name="exampoints">
              <exampoints :examinationId="exercisesForm.id" ref="childExampoints"></exampoints>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import jsonData from '@/assets/json/data.json'
import scoreCard from '@/views/modules/exercises/scoreCard.vue'
import selfinspectionCard from '@/views/modules/exercises/selfinspectionCard.vue'
import cueCard from '@/views/modules/exercises/cueCard.vue'
import exampoints from '@/views/modules/exercises/exampoints.vue'
import Vue from 'vue'
import axios from 'axios'
export default {
  components: {
    scoreCard,
    selfinspectionCard,
    cueCard,
    exampoints
  },
  data () {
    return {
      typeList: jsonData.typeList,
      statusList: jsonData.statusList,
      genderList: jsonData.genderList,
      searchForm: {},
      // 带随访数目
      dataList: [],
      selectDataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      tableHeight: 0,
      exercisesDialog: false,
      uploadProgress: 0,
      exercisesForm: {
        dept: '',
        examNameCode: '',
        examText: '',
        examPoints: '',
        examVideoUrl: '',
        examImageUrl: '',
        examVideoUrlBak: '',
        examVideoTime: null
      },
      exercisesFormRules: {
        dept: [{ required: true, message: '试题类型不能为空', trigger: 'change' }],
        examNameCode: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
        examText: [{ required: true, message: '习题题干不能为空', trigger: 'change' }],
        examPoints: [{ required: true, message: '注意事项及说明不能为空', trigger: 'change' }],
        examVideoUrl: [{ required: true, message: '视频不能为空', trigger: 'change' }]
      },
      deptLoading: false,
      examLoading: false,
      saveLoading: false,
      // 顶部保存loading
      deptOptions: [],
      examOptions: [],
      activeName: 'scoreCard',
      videoUrl: null,
      // new upload
      url: ''

    }
  },
  computed: {
    headerToken () {
      return { Token: Vue.cookie.get('token') }
    }
  },
  created () {
    setTimeout(() => {
      this.url = this.$http.BASE_URL + `/tool/upload/uploadMultipartFile`

      this.tableHeight = this.$refs.tableBox.scrollHeight
    }, 100)
    this.getDataList()
    this.getDept()
  },
  methods: {
    // 上传视频 start
    successHandle (res, file) {
      this.$message.success('视频上传成功')
      this.exercisesForm.examVideoUrl = res.url
    },
    beforeUploadHandle (ev) {
      console.log(ev)
      // ev.target.files点击上传的；ev.dataTransfer.files拖拽上传
      // const files = ev.target.files || ev.dataTransfer.files
      const target = ev
      if (target) {
        if (window.createObjectURL !== undefined) {
          this.exercisesForm.examVideoUrlBak = URL.createObjectURL(target)
        } else if (window.URL !== undefined) {
          this.exercisesForm.examVideoUrlBak = URL.createObjectURL(target)
        } else if (window.webkitURL !== undefined) {
          this.exercisesForm.examVideoUrlBak = URL.createObjectURL(target)
        }
      }
      if (target && target.type.startsWith('video/')) {
        const video = document.createElement('video')
        video.preload = 'metadata'

        // 设置视频文件源
        video.src = URL.createObjectURL(target)

        // 加载元数据
        video.onloadedmetadata = () => {
          // this.exercisesForm.examVideoTime = video.duration
          let time = Math.ceil(video.duration)
          this.exercisesForm.examVideoTime = this.translateTime(time)
          URL.revokeObjectURL(video.src)
        }
      }
      setTimeout(() => {
        this.capture()
      }, 500)
    },
    capture () {
      // 创建canvas元素
      const canvas = document.createElement('canvas')
      // 设置canvas的画布的大小，画布的大小就决定了我们截图的大小
      canvas.width = this.$refs.video.videoWidth
      canvas.height = this.$refs.video.videoHeight
      // 绘制2D绘图空间并且截图大小及坐标设置
      /*
      drawImage()介绍
      第一个参数：图片源（你要从哪里截取图片）
      第二、三个参数：截取的起始坐标
      第四、五个参数：你要截多大
      */
      canvas.getContext('2d').drawImage(this.$refs.video, 0, 0, canvas.width, canvas.height)
      // canvas.toDataURL('image/png')
      // this.exercisesForm.examImageUrl = canvas.toDataURL('image/png')
      // 上传
      const formData = new FormData()
      formData.append('file', canvas.toDataURL('image/png'))
      console.log(formData)
      axios.post('/tool/upload/uploadBase64File', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        // 处理响应
        this.exercisesForm.examImageUrl = response.data.url
        // console.log(response.data.url)
      })
      .catch(error => {
        // 处理错误
        console.error(error)
      })
    },
    handleProgress (event, file, fileList) {
      this.uploadProgress = parseInt(event.loaded / event.total * 100)
      console.log(`当前进度：${this.uploadProgress}%`)
    },
    customRequest (options) {
      const formData = new FormData()
      // 这里的 'file' 是后端接收文件的字段名
      formData.append('file', options.file)

      // 创建一个 XMLHttpRequest 实例用于上传文件
      const xhr = new XMLHttpRequest()
      xhr.open('POST', this.uploadUrl, true)

      xhr.onload = () => {
        if (xhr.status === 200) {
          options.onSuccess()
        } else {
          options.onError()
        }
      }

      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) {
          const percentComplete = (e.loaded / e.total) * 100
          // 调用进度更新函数
          options.onProgress({ percent: percentComplete })
        }
      }

      xhr.send(formData)
    },
    // 上传视频 end
    translateTime (timeStr) {
      let minute = Math.floor((timeStr % 3600) / 60) > 9 ? Math.floor((timeStr % 3600) / 60) : '0' + Math.floor((timeStr % 3600) / 60)
      let second = Math.floor(timeStr % 60) > 9 ? Math.floor(timeStr % 60) : '0' + Math.floor(timeStr % 60)
      return `${minute}:${second}`
    },
    computedGenderList (val) {
      let Arr = this.genderList.filter(item => {
        return item.value === String(val)
      })
      if (Arr.length > 0) {
        return Arr[0].label
      } else {
        return '暂无'
      }
    },
    computeduserLevelId (val) {
      if (val === 0) {
        return '非会员'
      } else {
        return `会员${val}级`
      }
    },
    computedStatus (val) {
      let Arr = this.statusList.filter(item => {
        return item.value === String(val)
      })
      if (Arr.length > 0) {
        return Arr[0].label
      } else {
        return '暂无'
      }
    },
    // 获取数据列表
    getDataList (page) {
      if (page) {
        this.pageIndex = page
      }
      this.$http({
        url: '/study/examination/list',
        method: 'get',
        params: {
          page: this.pageIndex,
          limit: this.pageSize,
          examName: this.searchForm.examName,
          examTypeName: this.searchForm.examTypeName
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
      })
    },

    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },

    clearHandle () {
      this.searchForm = {}
      this.pageIndex = 1
      this.getDataList()
    },
    handleSelectionChange (val) {
      this.selectDataList = val
    },
    showExercises () {
      // console.log(this.$store.state.user)
      this.exercisesForm = {
        dept: '',
        examNameCode: '',
        examText: '',
        examPoints: '',
        examVideoUrl: '',
        examImageUrl: '',
        examVideoUrlBak: '',
        examVideoTime: null
      }
      this.exercisesDialog = true
      setTimeout(() => {
        this.resetForm('exercisesForm')
        this.$refs.childScoreCard.updateData()
        this.$refs.childSelfinspectionCard.updateData()
        this.$refs.childCueCard.updateData()
        this.$refs.childExampoints.updateData()
      }, 10)
    },
    edit (params) {
      this.exercisesDialog = true
      setTimeout(() => {
        this.resetForm('exercisesForm')
        this.exercisesForm = JSON.parse(JSON.stringify(params))
        this.exercisesForm.dept = this.exercisesForm.examTpyeCoded
        this.exercisesForm.examNameCode = String(this.exercisesForm.examNameCode)
        this.exercisesForm.examVideoUrlBak = this.exercisesForm.examVideoUrl
        this.getDept()
        this.getExam(this.exercisesForm.dept)
        this.$refs.childScoreCard.updateData()
        this.$refs.childSelfinspectionCard.updateData()
        this.$refs.childCueCard.updateData()
        this.$refs.childExampoints.updateData()
      }, 10)
    },
    exercisesFormSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveLoading = true
          let examName = this.examOptions.filter(val => val.id === this.exercisesForm.examNameCode)[0].examName
          let examTypeName = this.deptOptions.filter(val => val.id === this.exercisesForm.dept)[0].dept
          if (this.exercisesForm.id) {
            this.$http({
              url: '/study/examination/update',
              method: 'post',
              data: {
                examTpyeCoded: this.exercisesForm.dept,
                examTypeName,
                examNameCode: this.exercisesForm.examNameCode,
                examName,
                examText: this.exercisesForm.examText,
                examPoints: this.exercisesForm.examPoints,
                examVideoUrl: this.exercisesForm.examVideoUrl,
                examImageUrl: this.exercisesForm.examImageUrl,
                examVideoTime: this.exercisesForm.examVideoTime,
                createOperatorId: this.$store.state.user.id,
                id: this.exercisesForm.id
              }
            }).then(({ data }) => {
              // console.log(data)
              if (data && data.code === 0) {
                this.saveLoading = false
                this.$message.success('保存成功，请继续上传相关资料')
              } else {
                this.saveLoading = false
              }
            })
          } else {
            this.$http({
              url: '/study/examination/save',
              method: 'post',
              data: {
                examTpyeCoded: this.exercisesForm.dept,
                examTypeName,
                examNameCode: this.exercisesForm.examNameCode,
                examName,
                examText: this.exercisesForm.examText,
                examPoints: this.exercisesForm.examPoints,
                examVideoUrl: this.exercisesForm.examVideoUrl,
                examImageUrl: this.exercisesForm.examImageUrl,
                examVideoTime: this.exercisesForm.examVideoTime,
                createOperatorId: this.$store.state.user.id,
                id: this.exercisesForm.id
              }
            }).then(({ data }) => {
              // console.log(data)
              if (data && data.code === 0) {
                this.saveLoading = false
                this.$message.success('保存成功，请继续上传相关资料')
              } else {
                this.saveLoading = false
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 获取科室
    getDept (val) {
      this.deptLoading = true
      this.$http({
        url: '/study/dept/queryAll',
        method: 'get',
        params: {
          page: 1,
          limit: 10,
          deptId: val
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.deptOptions = data.list
          // console.log(data)
          this.deptLoading = false
        } else {
          this.deptOptions = []
          this.deptLoading = false
        }
      })
    },
    // 科室变更
    deptChange () {
      this.exercisesForm.examNameCode = ''
      if (this.exercisesForm.dept) {
        this.getExam(this.exercisesForm.dept)
      } else {
        this.examOptions = []
      }
    },
    // 获取科室
    getExam (val) {
      this.examLoading = true
      this.$http({
        url: '/study/examnametype/queryAll',
        method: 'get',
        params: {
          page: 1,
          limit: 10,
          deptId: val
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.examOptions = data.list
          this.examLoading = false
        } else {
          this.examOptions = []
          this.examLoading = false
        }
      })
    },

    handleClick (tab, event) {
      console.log(tab, event)
      this.activeName = tab.name
      // if(this.activeName == '')
    },
    delItem (val) {
      const h = this.$createElement
      this.$msgbox({
        title: '删除',
        message: h('p', { style: 'width: 300px;display:flex;' }, [
          h('i', { class: 'el-icon-delete', style: 'color: red;font-size: 24px;font-weight:600;margin-right: 6px' }, ''),
          h('span', null, `请确认是否删除该条题干？`)
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            this.$http({
              url: `/study/examination/deleteByExaminationId?examinationId=${val.id}`,
              method: 'post'
            }).then(({ data }) => {
              if (data && data.code === 0) {
                instance.confirmButtonLoading = false
                done()
                this.$message.success('删除成功')
                this.getDataList()
              } else {
                instance.confirmButtonLoading = false
                done()
              }
            })
            setTimeout(() => {
              //
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
              }, 300)
            }, 3000)
          } else {
            done()
          }
        }
      })
    }
  }
}
</script>
<style lang="scss">
.exercises-box {
  .el-dialog__body {
    height: calc(100% - 54px) !important;
    padding: 20px 20px;
    overflow: auto;
    // display: flex;
    // flex-direction: column;
  }

  .inner {
    .table-box {
      flex: 1;
      width: 100%;
    }
  }

  .top-box {
    border: 1px solid rgba(10, 115, 78, 0.2);
    border-radius: 6px;
    overflow: hidden;
    margin-bottom: 20px;

    .title {
      width: 100%;
      height: 40px;
      line-height: 40px;
      color: #333;
      font-size: 16px;
      font-weight: 600;
      padding-left: 10px;
      margin: 0;
      margin-bottom: 20px;
      background: rgba(10, 115, 78, 0.2);
      display: flex;
      justify-content: space-between;
    }
  }

  .bottom-box {
    // flex: 1;
    min-height: 400px;
    max-height: 1000px;
    overflow: auto;

    .tab-inner {
      padding: 0 10px;
    }
  }
}

.upload-box {
  height: 60px;

  .el-upload--text {
    position: absolute;
    left: 330px;
  }

  .el-upload-list {
    width: 300px;
    position: absolute;
    left: 0;
    top: 0;
  }

  .el-upload__tip {
    margin-top: 0;
    font-size: 14px;
  }
}
</style>
